/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.mybatisplus.handler;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.moon.framework.autoconfigure.secure.AuthUtils;
import org.moon.framework.autoconfigure.secure.domain.AuthInfo;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * 审计字段自动填充
 * @author moon
 */
@AutoConfigureAfter({MybatisPlusAutoConfiguration.class})
@Configuration
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

	private final static String CREATE_BY = "createBy";
	private final static String UPDATE_BY = "updateBy";
	private final static String CREATE_DEPT = "createDept";
	private final static String CREATE_TIME = "createTime";
	private final static String UPDATE_TIME = "updateTime";

	@Override
	public void insertFill(MetaObject metaObject) {
		LocalDateTime now = LocalDateTime.now();
		if(metaObject.getValue(CREATE_TIME)==null){
			this.strictInsertFill(metaObject,CREATE_TIME,LocalDateTime.class,now);
		}
		if(metaObject.getValue(UPDATE_TIME)==null){
			this.strictInsertFill(metaObject,UPDATE_TIME,LocalDateTime.class,now);
		}
		AuthInfo info = null;
		try {
			info = AuthUtils.getAuthInfo();
		}catch (Exception e){
		}
		if(info==null) {
			return;
		}
		if(metaObject.getValue(CREATE_BY)==null){
			this.strictInsertFill(metaObject,CREATE_BY,Integer.class,info.getId());
		}
		if(metaObject.getValue(UPDATE_BY)==null){
			this.strictInsertFill(metaObject,UPDATE_BY,Integer.class,info.getId());
		}
		if(metaObject.getValue(CREATE_DEPT)==null){
			this.strictInsertFill(metaObject,CREATE_DEPT,Integer.class,info.getDeptId());
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		LocalDateTime now = LocalDateTime.now();
		if(metaObject.getValue(UPDATE_TIME)==null){
			this.strictInsertFill(metaObject,UPDATE_TIME,LocalDateTime.class,now);
		}
		AuthInfo info = null;
		try {
			info = AuthUtils.getAuthInfo();
		}catch (Exception e){
		}
		if(info==null) {
			return;
		}
		if(metaObject.getValue(UPDATE_BY)==null){
			this.strictInsertFill(metaObject,UPDATE_BY,Integer.class,info.getId());
		}
	}
}